/**
 * 操作基本数据
 */

/**
 * 通过服务器接口调用微信数据
 *
 * @param {Object}
 *            openId 当前调用用户ID
 * @param {Object}
 *            type 调用类型
 * @param {Object}
 *            data 回调数据
 * @param {Object}
 *            sucesscallback 调用成功回调函数,回调参数：data, status, xhr
 * @param {Object}
 *            errcallback 调用失败回调函数,回调参数：xhr, error, exception
 */
function bidgeToWeixin(openId, type, data, sucesscallback, errcallback) {
		if (openId.indexOf("#") > -1) {
			openId = openId.replace("#", "");
		}
		$.ajax({
			url: actionStr,
			type: 'POST',
			data: JSON.stringify(popRequest(type, openId, popBody(type, data))),
			dataType: 'json',
			contentType: 'application/json'
		}).then(sucesscallback).fail(
			errcallback || function(xhr, error, exception) {
				closemaskLoading();
				alert(exception.toString());
			});
	}
	/**
	 * 保存数据
	 */

function saveData(data) {
	if (openId.indexOf("#") > -1) {
		openId = openId.replace("#", "");
	}
	var loc = {
		Latitude: 29.579916,
		Longitude: 115.98905
	};

	loc.Latitude = parseFloat(data.destination.location.lat) * 1000000;
	loc.Longitude = parseFloat(data.destination.location.lng) * 1000000;

	var destination = {
		Name: data.destination.name,
		City: data.destination.city.citycode || '',
		Loc: loc
	};
	var members = [];
	members.push(openId);

	var dataStr = {
		Title: data.title,
		ValidDate: data.endtime + ' 23:59:59',
		StartDate: data.starttime + ' 00:00:00',
		Destination: destination,
		MemberStatus: members
	};
	/*
	 * var jsonData = popRequest('CreateTrip', openId, popBody('CreateTrip',
	 * dataStr)); saveDataLocal(jsonData); //将数据存储到本地
	 */
	bidgeToWeixin(openId, 'CreateTrip', dataStr, function(data, status, xhr) {
		alert('创建旅程成功!');
		window.location.href = "trip_list.html?openid=" + openId;
	}, function(xhr, error, exception) {
		alert('创建旅程失败!');
		console.log(exception.toString());
	});
}

function editData(data) {
		var loc = {
			Latitude: 29.579916,
			Longitude: 115.98905
		};

		loc.Latitude = parseFloat(data.destination.location.lat) * 1000000;
		loc.Longitude = parseFloat(data.destination.location.lng) * 1000000;

		var destination = {
			Name: data.destination.name,
			City: data.destination.city.citycode || '',
			Loc: loc
		};
		var dataStr = {
			TripID: data.tripId,
			Title: data.title,
			ValidDate: data.endtime + ' 23:59:59',
			StartDate: data.starttime + ' 00:00:00',
			Destination: destination,
			TripLeader: data.TripLeader || ''
		};
		/*
		 * var jsonData = popRequest('CreateTrip', openId, popBody('CreateTrip',
		 * dataStr)); saveDataLocal(jsonData); //将数据存储到本地
		 */
		bidgeToWeixin(openId, 'EditTrip', dataStr, function(data, status, xhr) {
			alert('修改旅程成功!');
			window.location.href = "trip_list.html?openid=" + openId;
		}, function(xhr, error, exception) {
			alert('修改旅程失败!');
			console.log(exception.toString());
		});
	}
	/**
	 * 将数据存储到本地
	 *
	 * @param {Object}
	 *            data 数据对象
	 */

function saveDataLocal(data) {
		if (toString.apply(data) === '[object Object]') {
			var journeys = localStorage.journeylist ? $
				.parseJSON(localStorage.journeylist) : {};
			journeys[data.creater.userid] = data;
			var jsonStr = JSON.stringify(journeys);
			localStorage.journeylist = jsonStr;
			sessionStorage.journeylist = jsonStr;
		}
		return true;
	}
	/**
	 * 根据条件获取数据,默认返回整个数据集
	 *
	 * @param {Object}
	 *            tripId 需要编辑的旅程ID号
	 * @param {Object}
	 *            callback 回调函数
	 */

function getJourney(tripId, callback) {
	var dataStr = {
		"TripID": tripId
	};
	bidgeToWeixin(openId, 'TripDetail', dataStr, callback);
}

/**
 * 通过Ajax调用接口获取好友列表 ，需要添加js:jsonMsg.js
 *
 * @param {Object}
 *            openId
 * @param {Object}
 *            callback 回调函数
 */

function getFriendsListByAjax(openId, callback) {
		bidgeToWeixin(openId, 'ListFriends', {}, function(data, status, xhr) {
			if (data && data.portalResp.Data.Profiles) {
				callback(data.portalResp.Data.Profiles);
			} else {
				callback(null);
			}
		});
	}
	/**
	 * 界面上一些基本操作
	 */
	/**
	 * iframe页面调用，将选择的值传递过来
	 *
	 * @param {Object}
	 *            render 值绑定对象
	 * @param {Object}
	 *            value 值
	 * @param {Object}
	 *            data 绑定的值
	 */

function setIframeContentValue(render, value, data) {
		var ren = $('#' + render);
		ren.html(value);
		if (data) {
			for (var k in data) {
				ren.data(k, data[k]);
			}
		}
		closeIframeContent();
	}
	/**
	 * 关闭iframe嵌套窗口
	 */

function closeIframeContent() {
		$('.iframe-containter').hide().empty();
		$('body').css({
			'overflow-y': 'auto'
		});
	}
	/**
	 * 将要调用的二级页面嵌套调用
	 *
	 * @param {Object}
	 *            src 调用路径
	 */

function setIframeSrc(src) {
		$('body').css({
			'overflow-y': 'hidden'
		});

		//console.log($('body').height());
		var iframeContainer = $('.iframe-containter').css({
				'top': $('body').scrollTop()
			}).empty().css({
				'left': '0%'
			}).show(),
			iframe = $('<iframe>').attr({
				'src': src
			}).appendTo(iframeContainer);
		iframeWin = iframe[0].contentWindow;
	}
	/**
	 * 获取元素父元素
	 *
	 * @param {Object}
	 *            par 元素,$对象
	 * @param {Object}
	 *            filter 过滤条件
	 */

function _getTarparanet(par, filter) {
	return (par[0][filter['key']] == filter['value'] || par[0][filter['key']] == 'BODY') ? par : _getTarparanet(par.parent(), filter);
}

function _getTarparanetByClass(par, filter) {
		return par.hasClass(filter) ? par : _getTarparanetByClass(par.parent(), filter);
	}
	/**
	 * 初始界面上的数据
	 *
	 * @param {Object}
	 *            data 数据集
	 */

function initJourneyInfo(data) {
		if (data) {
			$('*[data-column]').each(function() {
				var tar = $(this),
					column = tar.attr('data-column'),
					d = data;
				switch (column) {
					case 'title':
						tar.val(d.Title);
						break;
					case 'starttime':
						d.StartDate = d.StartDate || d.ValidDate;
						tar.html(d.StartDate.replace(/年|月/g, '-').replace('日', ''));
						break;
					case 'endtime':
						tar.html(d.ValidDate.replace(/年|月/g, '-').replace('日', ''));
						break;
					case 'tripleader':
						tar.val(d.TripLeader);
						break;
					case 'destination':
						tar.html(d.Destination.Name).data('address', {
							location: {
								lat: d.Destination.Loc.Latitude,
								lng: d.Destination.Loc.Longitude,
							},
							name: d.Destination.Name,
							city: {
								citycode: d.City
							}
						});
						break;
						/*
						 * case 'friendslist': var lis = []; for (var i = 0, l = d.length; i <
						 * l; i++) { lis.push($('<li>').data('user', d).append($('<img>').attr({
						 * 'src': d[i].photo }).addClass('photo-img ' + (i == 6 ?
						 * 'user-leader' : ''))) .append($('<span>').addClass('photo-img-marker'))
						 * .append($('<span>').html(d[i].name))); } $('ul',
						 * tar).append(lis); break;
						 */
					default:
						tar.val(d);
						break;
				}
			});
		}
	}
	/**
	 * 更新旅程状态
	 *
	 * @param {Object}
	 *            tripId 旅程ID
	 * @param {Object}
	 *            stats 状态值,Terminate 结束旅程
	 */

function updateTripStatus(tripId, stats) {
		var dataStr = {
			"TripID": tripId,
			"TripStatus": stats
		};
		bidgeToWeixin(openId, 'EditTripStatus', dataStr,
			function(data, status, xhr) {
				if (stats == 'Active') {
					// window.location.href = "trip_voice.html?openid=" + openId
					// + "&tripid=" + tripId;
					window.location.href = "inJourney.html?openid=" + openId + "&tripid=" + tripId;
				} else {
					window.location.href = "trip_list.html?openid=" + openId;
				}
			});
	}
	/**
	 * 创建加载等待框
	 */

function showMaskLoading() {
		/*$('<div>').addClass('k-mask-container').css({
				'height': window.screen.availHeight + 'px',
				'line-height': window.screen.availHeight + 'px'
			})
			.append($('<div>').addClass('k-mask-logding').html('请稍后...'))
			.appendTo($('body').css({
				'overflow-y': 'hidden'
			}));*/
	}
	/**
	 * 关闭创建加载等待框
	 */

function closemaskLoading() {
		/*$('.k-mask-container').hide('slow').remove();
		$('body').css({
			'overflow-y': 'auto'
		})*/
	}
	/**
	 * 初始化加载时加载
	 */
$ && $(function() {
	$('.js_back').on('click', function() {
		parentwin && parentwin.closeIframeContent();
	});
});

Array.prototype.sum = function() {
	for (var sum = i = 0; i < this.length; i++)
		sum += parseInt(this[i]);
	return sum;
};